package studykana.database;

import java.util.ArrayList;

import studykana.models.Alphabet;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class Databasehandler {

	private static final String TABLE_ALPHABET = "Alphabet";
	private static final String ID = "Id";
	private static final String HIRAGANA = "Hiragana";
	private static final String KATAKANA = "Katakana";
	private static final String ROMAJI = "Romaji";

	Context context;

	public Databasehandler(Context context) {
		this.context = context;
	}

	public Alphabet getAlphabetById(int id) {
		for (Alphabet item : AppData.listAllAlphabet) {
			if (item.getId() == id)
				return item;
		}
		return null;
	}

	public void getAllAlphabet(SQLiteDatabase db) throws SQLException {
		String sql = "Select " + ID + "," + HIRAGANA + "," + KATAKANA + ","
				+ ROMAJI + " From " + TABLE_ALPHABET;
		Cursor cursor = db.rawQuery(sql, null);
		if (cursor == null) {
			throw new SQLException("Get all alphabet failed!");
		}
		AppData.listAllAlphabet = new ArrayList<Alphabet>();
		if (cursor.moveToFirst()) {
			do {
				Alphabet alphabet = new Alphabet(Integer.parseInt(cursor
						.getString(0)), cursor.getString(1),
						cursor.getString(2), cursor.getString(3));
				AppData.listAllAlphabet.add(alphabet);
			} while (cursor.moveToNext());
		}
		cursor.close();
	}

	public String getRomajiByHira(String hiragana) {
		for (Alphabet item : AppData.listAllAlphabet) {
			if (item.getHiragana().equals(hiragana)) {
				return item.getRomaji();
			}
		}
		return null;
	}

	public String getRomajiByKata(String katakana) {
		for (Alphabet item : AppData.listAllAlphabet) {
			if (item.getKatakana().equals(katakana)) {
				return item.getRomaji();
			}
		}
		return null;
	}
}
